import { createCanvas } from 'canvas';
import { Scene } from './Scene';
import mkdirp from 'mkdirp';
import path from 'path';
import * as fs from 'fs';

export interface ProjectProperties {
	width: number;
	height: number;
	fps: number;

	outputDirectory: string;
}

export interface TapeSegment {
	scene: Scene;
	length: number;
}

export class Project {
	constructor(private properties: ProjectProperties) {
	}

	public addScene(segment: TapeSegment): Project {
		this.scenes.push(segment);
		return this;
	}

	public render() {
		const outDir = path.resolve(this.properties.outputDirectory);
		console.log(`Output directory: ${outDir}`);
		mkdirp.sync(outDir);

		const canvas = createCanvas(this.properties.width, this.properties.height);
		const ctx = canvas.getContext('2d');
		let absoluteFrameCount = 0;

		for (const scene of this.scenes) {
			for (let i = 0; i < scene.length; i++) {
				scene.scene.render(ctx, i, i * (1 / this.properties.fps));
				const buf = canvas.toBuffer('image/png');
				fs.writeFileSync(`${outDir}/f${absoluteFrameCount.toString().padStart(5, '0')}.png`, buf);
				ctx.clearRect(0, 0, this.properties.width, this.properties.height);
				++absoluteFrameCount;
			}
		}
	}

	private scenes: TapeSegment[] = [];
}
